package com.itheima.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.properties.JwtProperties;
import com.itheima.service.DeptService;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import com.itheima.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper,Emp> implements EmpService {
    @Autowired
    private DeptService deptService;
    @Autowired
    private EmpExprService empExprService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 条件分页查询
     * @param param
     * @return
     */
    @Override
    public PageResult pageQuery(EmpQueryParam param) {
        //StrUtil.isEmpty(param.getName());   // null ""
        //StrUtil.isBlank(param.getName());   // null ""  "          "
//        //1.构造查询条件
//        Wrappers.<Emp>lambdaQuery().like(StrUtil.isNotBlank(param.getName()),Emp::getName,param.getName())
//                .eq(ObjectUtil.isNotNull(param.getGender()),Emp::getGender,param.getGender())
//                .between(ObjectUtil.isNotNull(param.getBegin())||ObjectUtil.isNotNull(param.getEnd()),Emp::getEntryDate,param.getBegin(),param.getEnd());
//        //2.发起分页查询
//        Page<Emp> page = Page.of(param.getPage(), param.getPageSize());
//        page.addOrder(OrderItem.desc("update_time"));
//            //page方法
//        Page<Emp> empPage = this.page(page);

        //1,2 简化（主流） lambdaQuery() 构建查询条件并且发起分页查询
        Page<Emp> page = Page.of(param.getPage(), param.getPageSize());
        page.addOrder(OrderItem.desc("update_time"));
        Page<Emp> empPage = this.lambdaQuery().like(StrUtil.isNotBlank(param.getName()), Emp::getName, param.getName())
                .eq(ObjectUtil.isNotNull(param.getGender()), Emp::getGender, param.getGender())
                .between(ObjectUtil.isNotNull(param.getBegin()) || ObjectUtil.isNotNull(param.getEnd()), Emp::getEntryDate, param.getBegin(), param.getEnd())
                .page(page);
        //3.处理部门名称
        List<Emp> empList = empPage.getRecords();
        Set<Integer> deptIds = empList.stream().map(Emp::getDeptId).collect(Collectors.toSet());
        List<Dept> deptList = deptService.listByIds(deptIds);
        Map<Integer, String> DeptMap = deptList.stream().collect(Collectors.toMap(Dept::getId, Dept::getName));
        empList.forEach(emp -> {
            emp.setDeptName(DeptMap.getOrDefault(emp.getDeptId(),"暂未分配部门"));
        });
        //4.封装分页结果集
        return new PageResult(empPage.getTotal(),empList);
    }

    /**
     * 保存员工信息和员工的工作经历信息
     * @param emp
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveEmp(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        emp.setCreateTime(LocalDateTime.now());
        //向emp表插入Emp基本数据
        save(emp);
        //向emp_expr表插入经历
        List<EmpExpr> exprList = emp.getExprList();
        exprList.forEach(empExpr -> empExpr.setEmpId(emp.getId()));
        empExprService.saveBatch(exprList);
    }

    /**
     * 查询回显员工基本信息及工作经历信息
     * @param id
     * @return
     */
    @Override
    public Emp getEmpById(Integer id) {
        Emp emp = getById(id);
        emp.setExprList(empExprService.list(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId,emp.getId())));
        return emp;
    }

    /**
     * 修改员工及工作经历信息
     * @param emp
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateEmp(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        updateById(emp);
        // 根据id批量删除员工的工作经历信息
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId,emp.getId()));
        // 批量保存员工的工作经历信息
        List<EmpExpr> exprList = emp.getExprList();
        if (CollectionUtil.isNotEmpty(exprList)){
            exprList.forEach(empExpr -> {empExpr.setEmpId(emp.getId());});
        }
        empExprService.saveBatch(exprList);
    }

    /**
     * 批量删除员工及工作经历信息
     * @param ids
     */
    @Override
    public void removeEmpsByIds(List<Integer> ids) {
        removeByIds(ids);
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().in(EmpExpr::getEmpId,ids));
    }

    /**
     * 员工登录
     * @param emp
     * @return
     */
    @Override
    public LoginInfo login(Emp emp) {
        Emp loginEmp = lambdaQuery().eq(Emp::getUsername, emp.getUsername())
                .eq(Emp::getPassword, emp.getPassword())
                .one();
        if (ObjectUtil.isNotEmpty(loginEmp)){
            //验证成功 生成token
            HashMap<String, Object> map = new HashMap<>();
            map.put("id",loginEmp.getId());
            map.put("name",loginEmp.getName());
            map.put("username",loginEmp.getUsername());
            String token = JwtUtil.createJWT(jwtProperties.getSecretKey(), jwtProperties.getTtl(), map);
            //封装返回对象
            LoginInfo loginInfo = LoginInfo.builder()
                    .id(loginEmp.getId())
                    .name(loginEmp.getName())
                    .username(loginEmp.getUsername())
                    .token(token)
                    .build();
            return loginInfo;
        }
        return null;
    }
}
